package com.upc.tp.timeplanning.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.upc.tp.timeplanning.entity.ResBody;
import com.upc.tp.timeplanning.utils.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String,Object> map=new HashMap<>();
        ResBody resObj = new ResBody();
        String token=request.getHeader("token");
        try{
            JwtUtil.SelectToken(token);
            return true;
        }catch (Exception e) {
            resObj.setCode(0);
            resObj.setMsg("Unavailable Token");
        }
        String json=new ObjectMapper().writeValueAsString(resObj);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);

        return false;
    }

}
